package com.zhangxiaofanfan.hotcode.third;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-24 10:33:57
 */
public class HotCode012 {
    public static void main(String[] args) {
        String s = "ADOBECODEBANC", t = "ABC";
        HotCode012 hotCode = new HotCode012();
        System.out.println(hotCode.minWindow(s, t));
    }

    public String minWindow(String s, String t) {
        if (s == null || t == null || s.length() < t.length()) {
            return "";
        }
        Map<Character, Integer> mapS = new HashMap<>();
        Map<Character, Integer> mapT = new HashMap<>();
        for (int i = 0; i < t.length(); i++) {
            mapS.put(s.charAt(i), mapS.getOrDefault(s.charAt(i), 0) + 1);
            mapT.put(t.charAt(i), mapT.getOrDefault(t.charAt(i), 0) + 1);
        }
        int index = -1, cnt = 0;
        for (int left = 0, right = t.length(); right <= s.length(); right++) {
            if (checkMapTInMapS(mapS, mapT)) {
                while (left < right && checkMapTInMapS(mapS, mapT)) {
                    mapS.put(s.charAt(left), mapS.get(s.charAt(left)) - 1);
                    if (mapS.get(s.charAt(left)) <= 0) {
                        mapS.remove(s.charAt(left));
                    }
                    left++;
                }
                if (index == -1) {
                    index = left - 1;
                    cnt = right - index;
                } else if (cnt > right - left + 1) {
                    index = left - 1;
                    cnt = right - index;
                }
            }
            if (right < s.length()) {
                mapS.put(s.charAt(right), mapS.getOrDefault(s.charAt(right), 0) + 1);
            }
        }
        return index == - 1 ? "" : s.substring(index, index + cnt);
    }

    public boolean checkMapTInMapS(Map<Character, Integer> mapS, Map<Character, Integer> mapT) {
        if (mapS.size() < mapT.size()) {
            return false;
        }
        for (Character c : mapT.keySet()) {
            if (mapT.get(c) > mapS.getOrDefault(c, 0)) {
                return false;
            }
        }
        return true;
    }
}
